<?php

declare (strict_types = 1);

namespace App\Middleware\Auth;

use App\Constants\ErrorCode;
use App\Constants\RedisKey;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Hyperf\Utils\Context;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\{ResponseInterface,ServerRequestInterface};
use Psr\Http\Server\{MiddlewareInterface,RequestHandlerInterface};
use App\Utils\Redis;
use App\Utils\ApiUtils;

class RoleMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    protected $redis;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
        $this->redis = $container->get(Redis::class);
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 根据上下文里面的用户信息判断用户是否存在该路由的访问权限
        $user_info = Context::get('jwt_token');
        $server = $request->getServerParams();
        if (!in_array($user_info['uid'],config('web.super'))){
            // 使用 request_uri 判断用户是否有该路由的访问权限
            $permission_list = $this->redis->get(RedisKey::USER_AUTH_KEY.$user_info['uid']);
            // 前端路由规则  /#/main/AuthorityManager/RoleManage  匹配最后一串字符串
            if (!in_array($server['request_uri'],json_decode($permission_list))){
                return $this->response->json(ApiUtils::send(ErrorCode::ERR_BUESSUS, '没有访问权限'));
            }
        }
        return  $handler->handle($request);
    }

}